/*
 * Copyright (c) 2006-2021, Ulandlink Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-12-12     zkw         first version
 */

#include <rtthread.h>
#include "app_websocket_mgnt_sm.h"
#include "app_websocket_mgnt_mp.h"
#include "app_websocket_mgnt_util.h"
#include "app_websocket_mgnt_srv.h"

#define LOG_TAG "ocpp.websocket.srv"
#define LOG_LVL LOG_LVL_INFO
#include "ulog.h"

os_mq_t app_webclient_tx_msg_handle;
os_mq_t app_webclient_rx_msg_handle;

static void web_client_timer_bck(void *parameter) {
    app_webclient_timer_msg_post();
}

static void websocket_client_tx_entry(void *param) {
    app_webclient_tx_msg_handle = os_mq_create("web_tx_msg", 50);
    if (app_webclient_tx_msg_handle == RT_NULL) {
        LOG_E("app_wbesocket_msg_handle NULL");
        return;
    }

    if (!app_webclient_tx_msg_tab_init()) {
        LOG_E("app_webclient_msg_tab_init err");
        return;
    }

    app_webclient_tx_sm_init();
    os_mq_data msg = {0};

    while (1) {
        // rt_thread_mdelay(1000);
        memset(&msg, 0, sizeof(os_mq_data));
        if (os_mq_recv(app_webclient_tx_msg_handle, &msg, RT_WAITING_FOREVER)) {
            app_webclient_tx_msg_proc(&msg);
        }
        os_mq_free_mem(&msg);
    }
}

static void websocket_client_rx_entry(void *param) {
    app_webclient_rx_msg_handle = os_mq_create("web_rx_msg", 50);
    if (app_webclient_rx_msg_handle == RT_NULL) {
        LOG_E("app_wbesocket_rx_msg_handle NULL");
        return;
    }
    if (!app_webclient_rx_msg_tab_init()) {
        LOG_E("app_webclient_msg_tab_init err");
        return;
    }
    app_webclient_rx_sm_init();
    os_mq_data msg = {0};
    while (1) {

        memset(&msg, 0, sizeof(os_mq_data));
        if (os_mq_recv(app_webclient_rx_msg_handle, &msg, RT_WAITING_FOREVER)) {
            app_webclient_rx_msg_proc(&msg);
        }
        os_mq_free_mem(&msg);
    }
}

int32_t app_websocket_mgnt_init(void) {
    rt_thread_t webclient_tx = RT_NULL;
    rt_thread_t webclient_rx = RT_NULL;

    webclient_tx = rt_thread_create("websocket_tx", websocket_client_tx_entry, RT_NULL, 3072, 17, 10);
    if (webclient_tx == RT_NULL) {
        LOG_E("webclient_tx thread  create error");
        return -1;
    }
    webclient_rx = rt_thread_create("websocket_rx", websocket_client_rx_entry, RT_NULL, 3072, 17, 10);
    if (webclient_rx == RT_NULL) {
        LOG_E("webclient_rx thread  create error");
        return -1;
    }
    LOG_D("webclientthread create OK");
    rt_thread_startup(webclient_tx);
    rt_thread_startup(webclient_rx);
    return 0;
}
